package com.example.config.filter;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import com.google.gson.Gson;

public abstract class HttpRequestFilter extends OncePerRequestFilter{
	
	private final Logger log = LoggerFactory.getLogger(HttpRequestFilter.class);
	
	private final Gson gson = new Gson();
		
	public abstract boolean exclusive(String uri);

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		if (!exclusive(request.getRequestURI())) {
			print(request);
		}
		filterChain.doFilter(request, response);
	}
	
	public void print(HttpServletRequest request){
		log.info("----------  Start Print Requestion Info ----------");
		String url = request.getRequestURL().toString();
		String uri = request.getRequestURI();
		String method = request.getMethod();
		String remoteAddress = request.getRemoteAddr();
		String remoteHost = request.getRemoteHost();
		String requestedSessionId = request.getRequestedSessionId();
		log.info("URL={}    URI={}    Method={}", url, uri, method);
		log.info("Remote Address={}    Host={}    SessionId={}",
				remoteAddress, remoteHost, requestedSessionId);
		
		
			
			String userAgent = request.getHeader("User-Agent");
			String params = gson.toJson(request.getParameterMap());
			String cookie = null;

			Cookie[] cookies = request.getCookies();
			if (cookies != null) {
				Set<Cookie> collection = new HashSet<>();
				for (Cookie c : cookies) {
					collection.add(c);
					}
				cookie = gson.toJson(collection);
			}
			
		if(log.isDebugEnabled()){
			log.debug("Params={}", params);
			log.debug("User Agent={}", userAgent);
			log.debug("Cookies={}", cookie);
		}
		log.info("-----------  End Print Requestion Info -----------");
	}
}